package com.cn.demo.service;

import com.cn.demo.config.RabbitConst;
import com.cn.demo.entity.LeakyBucket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 漏桶算法业务类
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/12/6 14:12
 * @projectName demo
 */
@Service
@Slf4j
public class LeakyBucketService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 数据发送至mq中
     * @author: wangjf
     * @createTime: 2019/12/6 14:16
     * @param leakyBucket
     * @return void
     */
    public void sendMq(LeakyBucket leakyBucket){
        rabbitTemplate.convertAndSend(RabbitConst.LEAKY_BUCKET_EXCHANGE, RabbitConst.LEAKY_BUCKET_ROUTING_KEY, leakyBucket);
        //log.info("leakyBucket={}",leakyBucket);
    }

    /**
     * 功能描述: 使用线程池发送至mq
     * @author: wangjf
     * @createTime: 2019/12/6 14:58
     * @param leakyBucket
     * @return void
     */
    @Async("poolProduce")
    public void poolSendMq(LeakyBucket leakyBucket){
        rabbitTemplate.convertAndSend(RabbitConst.LEAKY_BUCKET_EXCHANGE, RabbitConst.LEAKY_BUCKET_ROUTING_KEY, leakyBucket);
        //log.info("leakyBucket={}",leakyBucket);
    }

    /**
     * 功能描述: 消费线程池
     * @author: wangjf
     * @createTime: 2019/12/6 15:15
     * @param leakyBucket
     * @return void
     */
    @Async("poolConsumer")
    public void poolConsumer(LeakyBucket leakyBucket) {

        log.info("leakyBucket={}",leakyBucket);
        try {
            Thread.sleep(10L);
        }catch (InterruptedException e){
            log.error("错误={}",e);
        }
    }

    /**
     * 功能描述: 普通消费
     * @author: wangjf
     * @createTime: 2019/12/6 15:19
     * @param leakyBucket
     * @return void
     */
    public void consumer(LeakyBucket leakyBucket){

        log.info("leakyBucket={}",leakyBucket);
        try {

            Thread.sleep(10L);
        }catch (InterruptedException e){
            log.error("错误={}",e);
        }
    }

}
